from sanic import Sanic
from sanic import Blueprint
from middleware.auth import auth_middleware
from middleware.main import error_hanlder
from tortoise.contrib.sanic import register_tortoise
from listener.limits import limits_start, limits_end
from ph_utils.config import load_env
from ph_utils.logger import sanic_logger_config

from route.main import main_route

load_env()  # 加载(.env, .env.production,.env.local)环境变量

app = Sanic(
    "{{= d.name }}",
    log_config=sanic_logger_config("{{= d.name }}", "/temp/logs"),
    env_prefix="APP_",
)
app.config.REAL_IP_HEADER = "x-real-ip"
app.config.AUTH_IGNORE_PATH = ["/system_monitor"]  # 不参与AUTH校验的请求
app.config.AUTH_API_PREFIX = "/api"  # AUTH校验时的请求前缀

# 连接 mysql
register_tortoise(
    app, db_url=app.config["MYSQL_URI"], modules={"models": ["model.auth"]}
)

# 监听器
app.register_listener(limits_start, "before_server_start")
app.register_listener(limits_end, "after_server_stop")

# 中间件
app.register_middleware(auth_middleware, "request")  # 权限校验

# 注册路由
home_group = Blueprint.group(main_route)
app.blueprint([home_group], url_prefix="/{{= d.name }}")

app.error_handler.add(Exception, error_hanlder)  # 添加全局的异常处理函数

if __name__ == "__main__":
    app.run(
        debug=app.config["DEBUG"],
        access_log=app.config["DEBUG"],
        auto_reload=app.config["DEBUG"],
        host="127.0.0.1" if app.config["DEBUG"] else "0.0.0.0",
        port=app.config["PORT"],
    )
